from flask import request

from api.libs.RedPrint import RedPrint
from core.tools import get_model_struct

api = RedPrint('common')


@api.route('/urls')
def get_urls():
    urls = get_model_struct()
    for k1 in urls:
        for k2 in urls[k1]:
            res = urls[k1][k2]
            urls[k1][k2] = [str(r) for r in res]
    return urls


@api.route('/search')
def search():
    from core.documents import APIModel
    from itertools import chain
    query_content = request.values['query_content']
    res = [model.relate_url for model in set(
        chain(APIModel.objects(url__icontains=query_content), APIModel.objects(comment__icontains=query_content)))]
    return res


@api.route('/progress')
def get_progress():
    from core.documents import TaskProgress
    key = request.values['key']
    task = TaskProgress.objects(key=key).first()
    return task.rate


@api.route('/progress/all')
def get_all_progress():
    from core.documents import TaskProgress
    res = {}
    for task in TaskProgress.objects():
        res[task.name] = [task.rate, task.key]
    for task in TaskProgress.objects():
        if task.rate == 100:
            task.delete()
    return res
